import { fabric } from 'fabric'
import { useBaseShapeConfig} from './useBaseShapeConfig'
import { drawArrow } from './tools'

/**
 * 元素插入画布相关
 * @param {*} canvasRef 
 * @returns 
*/
export const useShapeOpt = (canvasRef) => {
  // 基本配置
  const { getConfigByType } = useBaseShapeConfig()

  // 选择图标
  const getShapeByConfig = (type, config) => {
    let shape = null
    if (type === 'IText') {
      shape = new fabric.IText(config.text, config)
    } else if (type === 'Arrow') {
      shape = new fabric.Path(drawArrow(0, 0, 100, 100, 30, 30), config)
    }
    // else if (type === 'Image') {
    //   fabric.Image.fromURL(config.url, oImg => {
    //     oImg.scale(0.3)
    //     canvasRef.value.add(oImg)
    //   })
    // }
    else {
      shape = new fabric[type](config)
    }

    return shape
  }
  // 插入图形 interface type { IText, Image, Rect, Circle, Arrow }
  const insertShape = (type, url) => {
    const shapeConfig = getConfigByType(type, url)
    const shape = getShapeByConfig(type, shapeConfig)
    // vue3中会将add的元素转成Proxy，会导致元素控件无法响应，即无法缩放和删除等操作，所以需要使用markRaw将元素标记为原始对象
    const shapeRaw = markRaw(shape)
    canvasRef.value.add(shapeRaw)
    canvasRef.value.setActiveObject(shapeRaw)
  }

  return {
    insertShape
  }
}
